from flask_wtf import FlaskForm
from wtforms import StringField, DateField, TextAreaField, PasswordField, SelectField, validators, TimeField
from wtforms.validators import DataRequired, Length
from datetime import datetime, timedelta

class BookingForm(FlaskForm):
    name = StringField('姓名', validators=[DataRequired()])
    student_id = StringField('学号', validators=[DataRequired(), Length(min=8)])
    purpose = TextAreaField('用途', validators=[DataRequired()])
    date = DateField('预约日期', format='%Y-%m-%d', validators=[DataRequired()])

    date = DateField('预约日期', 
        format='%Y-%m-%d',
        validators=[
            DataRequired(),
            validators.InputRequired(message="请选择日期")
        ]
    )

    start_time = TimeField('开始时间', 
        validators=[
            DataRequired(),
            validators.InputRequired(message="请选择开始时间")
        ]
    )

    end_time = TimeField('结束时间',
        validators=[
            DataRequired(),
            validators.InputRequired(message="请选择结束时间")
        ]
    )

    def validate_date(self, field):
        """日期范围验证"""
        today = datetime.today().date()
        max_date = today + timedelta(days=7)
        
        if field.data < today:
            raise validators.ValidationError("不能选择过去的日期")
        if field.data > max_date:
            raise validators.ValidationError("只能预约未来7天内的日期")

    def validate_start_time(self, field):
        """开始时间验证"""
        now = datetime.now().time()
        if self.date.data == datetime.today().date() and field.data < now:
            raise validators.ValidationError("开始时间不能早于当前时间")

    def validate_end_time(self, field):
        """结束时间验证"""
        if self.start_time.data >= field.data:
            raise validators.ValidationError("结束时间必须晚于开始时间")
        
        start = datetime.combine(datetime.today(), self.start_time.data)
        end = datetime.combine(datetime.today(), field.data)
        if (end - start) > timedelta(hours=4):
            raise validators.ValidationError("单次预约时长不能超过4小时")


class LoginForm(FlaskForm):
    username = StringField('用户名', validators=[
        validators.DataRequired(message="用户名不能为空"),
        validators.Length(min=3, max=20)
    ])
    password = PasswordField('密码', validators=[
        validators.DataRequired(message="密码不能为空"),
        validators.Length(min=6)
    ])

class ApprovalForm(FlaskForm):
    action = SelectField('操作', choices=[('approve', '同意'), ('reject', '拒绝')])
    reason = TextAreaField('审批意见')
